package org.dreamwork.jasmine2.events;

import org.dreamwork.jasmine2.engine.IPostbackHandler;
import org.dreamwork.jasmine2.web.IWebContainer;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.util.WebControlCollection;
import org.dreamwork.util.NameValueCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-7-28
 * Time: 15:30:44
 */
public class PostbackDelegate implements IPostbackHandler {
    private static final Logger logger = LoggerFactory.getLogger (PostbackDelegate.class);
    private IWebContainer container;

    public PostbackDelegate (IWebContainer container) {
        this.container = container;
    }

    private void postbackData (IWebContainer container, NameValueCollection props) {
        if (container.isDataPostbacked ()) return;
        WebControlCollection coll = (WebControlCollection) container.getChildControls ();
        for (int i = 0; i < coll.count (); i ++) {
            IWebControl control = coll.getControl (i);
            if (control instanceof IPostbackHandler) {
                logger.debug ("postback data for control: " + control.getId () + "::" + control.getClass ().getName ());
                ((IPostbackHandler) control).postbackData (props);
            } if (control instanceof IWebContainer)
                postbackData ((IWebContainer) control, props);
        }
        container.setDataPostbacked (true);
    }

    public void postbackData (NameValueCollection props) {
        postbackData (container, props);
    }
}